package com.yonyou.pmclouds.productactive.service.rmiimpl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.conf.BuziOrderProperties;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.productactive.entity.BuziOrderInfoVO;
import com.yonyou.pmclouds.productactive.entity.EffectBuziInfoVO;
import com.yonyou.pmclouds.productactive.mapper.BuziJobUpdateLogMapper;
import com.yonyou.pmclouds.productactive.mapper.BuziOrderInfoMapper;
import com.yonyou.pmclouds.productactive.rmiitf.LicenseQuery;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service(version = ApplicationConsts.APPLICATION_VERSION, interfaceClass = LicenseQuery.class)
public class LicenseQueryImpl implements LicenseQuery {
    @Autowired
    private BuziOrderProperties properties;
    @Autowired
    private BuziOrderInfoMapper buziOrderInfoMapper;
    @Autowired
    private BuziJobUpdateLogMapper jobUpdateLogMapper;

    @Override
    public Date queryLastLicenseUpdateDate() {
        return jobUpdateLogMapper.getLastUpdateTime();
    }

    @Override
    public EffectBuziInfoVO[] queryTenantOrderEffectInDays(Date start, Date end, Date now) throws IllegalRequestArgException {
        if (start == null || end == null) {
            throw new IllegalRequestArgException();
        }
        // 查询生效日期时间区间内的租户
        String[] tenants = buziOrderInfoMapper.queryOrderTenantByDate(start, end);
        if (ArrayUtils.isEmpty(tenants)) {
            return null;
        }
        // 查询租户的实际时间
        EffectBuziInfoVO[] effectBuziInfos = new EffectBuziInfoVO[tenants.length];
        for (int i = 0; i < tenants.length; i++) {
            effectBuziInfos[i] = queryEffectUserOfTenant(tenants[i], now);
        }
        return effectBuziInfos;
    }

    @Override
    public int getMaxUserCountOfTenant(String tenantId, Date date) {
        EffectBuziInfoVO result = queryEffectUserOfTenant(tenantId, date);
        if (result == null) {
            return 0;
        }
        return result.getAccountQuantity();
    }

    @Override
    public EffectBuziInfoVO queryEffectUserOfTenant(String tenantId, Date date) {
        BuziOrderInfoVO[] orders = buziOrderInfoMapper.queryByTenant(tenantId);
        if (ArrayUtils.isEmpty(orders)) {
            return null;
        }
        List<BuziOrderInfoVO> buzis = new ArrayList<>();
        if (date == null) {
            date = new Date();
        }
        for (BuziOrderInfoVO order : orders) {
            if (!order.getProductId().equals(properties.getAppBuziId())) {
                continue;
            }
            // 指定日期后生效的订单不需要参与
            if (order.getActiveDate().after(date)) {
                continue;
            }
            buzis.add(order);
        }
        //  按照开始日期排序
        Collections.sort(buzis, new Comparator<BuziOrderInfoVO>() {
            @Override
            public int compare(BuziOrderInfoVO o1, BuziOrderInfoVO o2) {
                int result = o1.getActiveDate().compareTo(o2.getActiveDate());
                if (result != 0) {
                    return result;
                }
                if (o1.getPurType() == o2.getPurType()) {
                    return 0;
                }
                int p1 = o1.getPurType(), p2 = o2.getPurType();
                if (p1 == BuziOrderInfoVO.TYPE_ADD) {
                    p1 = 4;
                }
                if (p2 == BuziOrderInfoVO.TYPE_ADD) {
                    p2 = 4;
                }
                return p1 - p2;
            }
        });
        int sum = 0;
        int c = buzis.size() - 1;
        Date start = null, end = null;
        while (c >= 0)

        {
            // 如果是加购，则需要向前找不是加购的订单，并且累加总数
            BuziOrderInfoVO order = buzis.get(c);
            sum += order.getAccountQuantity();
            start = order.getActiveDate();
            if (end == null) {
                // 计算终止日期
                Calendar cal = Calendar.getInstance();
                cal.setTime(start);
                cal.add(Calendar.MONTH, order.getLease());
                end = cal.getTime();
            }
            if (order.getPurType() != BuziOrderInfoVO.TYPE_ADD) {
                break;
            }
            c--;
        }

        // 生成结果VO
        EffectBuziInfoVO result = new EffectBuziInfoVO();
        result.setAccountQuantity(sum);
        result.setActiveDate(start);
        result.setEndDate(end);
        result.setPkTenant(tenantId);
        result.setProductId(properties.getAppBuziId());
        result.setSkuId("");
        return result;
    }
}
